﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Windows.Forms;
using CommonTools;
using CommonTools.Controls;
using WeifenLuo.WinFormsUI.Docking;
using shop;
using shop.Bll;
using shop.Model;
using shop.Properties;
using shop.Bll.BasicInfo;

namespace shop.Logi
{
    /// <summary> 不用了 </summary>
    public partial class LogisticsFeeConfigForm : DockContent, IToolStripMergableForm, 
        IDocForm<shop.Model.LogisticsFeeConfig>
    {
        #region 属性, 字段

        /// <summary>
        /// 单据bll, 直接修改父类的内容
        /// </summary>
        public LogisticsFeeConfigBll DocBll { set; get; }

        /// <summary>
        /// 单据 直接修改父类的内容
        /// </summary>
        public LogisticsFeeConfig Doc
        {
            set
            {
                this._document = value ?? new LogisticsFeeConfig();
                this.LoadDoc();
            }
            get => this._document;
        }

        private LogisticsFeeConfig _document;

        private bool _isEditing = false;


        #endregion 属性, 字段

        #region 构造函数

        public LogisticsFeeConfigForm()
        {
            InitializeComponent();


            //检查权限, 需要在Doc赋值前修改
            RightHelper.CheckRight(this);


            //更换用户事件,检查权限 
            UserBll.UserChanged += () => RightHelper.CheckRight(this);


            //单据的Model, bll, 注意要先赋值bll,再赋值Model
            this.DocBll = new LogisticsFeeConfigBll();
            this.Doc = new LogisticsFeeConfig();

            cl_Method.CellComboboxData = new[] { "均摊", "按金额加价", "按数量加价", "按重量加价", "自定义" };
            

            //
            this.sta_Err.Text = "";
            this.sta_checked.Text = "";
            this.sta_LastTime.Text = "";
            this.sta_SelectionSum.Text = "";
        }

        public LogisticsFeeConfigForm(IDoc doc)
            : this()
        {
            this.Doc = doc as LogisticsFeeConfig;
        }

        #endregion 构造函数


        #region 实现IDocForm的接口: 新增,保存,创建窗口,显示窗口,

        /// <summary>
        /// 重载的保存方法, 会在实际保存前, 检查单据内容
        /// </summary>
        public bool Save()
        {
            this.Validate();

            for (int j = 0; j < this.grid.CurrentWorksheet.RowCount; j++)
            {
                CheckMethod(j);
            }

            //不能绑定数据的,在这里赋值, combobox 控件绑定数据有问题, 只能手动赋值给单据Doc
            Doc.OccurDate = Doc.PreparedDate = box_Date.Value;
            //int i = grid.BindingStartRow;
            //for (; i < this.grid.CurrentWorksheet.RowCount; i++)
            //{
            //    if (grid[cl_Method.Index, i].IsNull() == string.Empty && grid[cl_DistinguishCompany.Index, i].IsNull(0m) == 0)
            //    {
            //        break;
            //    }
            //}
            //i = i - grid.BindingStartRow;

            //if (Doc.Items.Count > i)
            //{
            //    //多了项目
            //    var ind = Doc.Items.Count - 1;
            //    var c = i - Doc.Items.Count + 2;
            //    for (int j = 0; j < c; j++)
            //    {
            //        Doc.Items.RemoveAt(ind);
            //        ind--;
            //    }
            //}

            if (this.DocBll.Save(this.Doc, UserBll.CurrentUser, out var err) == false)
            {
                //保存失败
                MessageBox.Show(err, Properties.Resources.systemInformation, MessageBoxButtons.OK,
                    MessageBoxIcon.Information);

                this.sta_Err.SetMessage(err, true);
                return false;
            }
            else
            {
                this.sta_Err.SetMessage(shop.Model.CN.Msg_Save, true);

                //将按钮的状态改成只读
                DocFormHelper.SetSaveStatus(SaveStatus.ReadOnly, this, toolSave, this.toolModify, toolSaveModify);
                //this.Doc.Items = DocBll.GetItems(Doc);
                //grid.ResetBindings(false);
                this.Doc = DocBll.GetDocByNum(Doc.Number);

                MessageTip.ShowOk(shop.Model.CN.Msg_Save);   // "保存成功!"


                //显示数据  这里都应该用绑定
                if (this.Doc.LastModifyTime != null)
                    this.sta_LastTime.Text = this.Doc.LastModifyTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                else
                    this.sta_LastTime.Text = "";

                return true;
            }
        }

        /// <summary> 删除 </summary>
        public void Delete()
        {
            if (MessageBox.Show(shop.Model.CN.Msg_wantToDeleteDoc,   //"确认要删除此单据吗?" 
                    Properties.Resources.systemInformation, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                != DialogResult.Yes)
            {
                return;
            }

            if (this.DocBll.Delete(this.Doc, UserBll.CurrentUser, out var err))
            {
                MessageTip.ShowOk(shop.Model.CN.Msg_DocIsDeleted);   // "单据已删除!"
                this.Close();  //直接关闭窗体

            }
            else
            {

                //删除失败
                MessageBox.Show(err, Properties.Resources.systemInformation, MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);

                this.sta_Err.SetMessage(err, true);
            }
        }

        private void LoadDoc()
        {
            //通过绑定数据的方式 加载单据内容
            this.docBindingSource.DataSource = new List<LogisticsFeeConfig>() { this.Doc };

            if (this.Doc != null && this.Doc.DocId > 0)
            {
                this.Doc.Items = DocBll.GetItems(Doc);


                if (this.Doc.LastModifyTime != null)
                    this.sta_LastTime.Text = this.Doc.LastModifyTime.Value.ToString("yyyy-MM-dd HH:mm:ss");
                else
                    this.sta_LastTime.Text = "";

                //保存状态, 这里会影响保存按钮的显示
                DocFormHelper.SetSaveStatus((this.Doc.DocId > 0 ? SaveStatus.ReadOnly : SaveStatus.CanSave),
                    this, this.toolSave, this.toolModify, this.toolSaveModify);
            }
            else
            {
                //控件赋值, 清空
                this.box_Date.Value = DateTime.Today;
                this.sta_LastTime.Text = "";
                //保存状态, 这里会影响保存按钮的显示
                DocFormHelper.SetSaveStatus(SaveStatus.CanSave, this, this.toolSave, this.toolModify, this.toolSaveModify);
            }

            grid.ResetBindings(false);
            //grid.DataSource = Doc;

            this.sta_Err.SetMessage(); //清空提示
        }


        /// <summary> 创建新窗体, 但是不显示出来 </summary>
        public IDocForm<LogisticsFeeConfig> CreateForm(IDoc doc)
        {
            return new LogisticsFeeConfigForm(doc);
        }

        #endregion 实现IDocForm的接口: 新增,保存,创建窗口,显示窗口,

        #region 上方菜单按钮

        /// <summary> 保存按钮, 实现三个状态切换: 保存,修改,保存修改 </summary>
        private void toolSave_Click(object sender, EventArgs e)
        {
            //直接保存
            this.Save();
        }

        /// <summary> 修改 </summary>
        private void toolModify_Click(object sender, EventArgs e)
        {
            if (toolSaveModify.Enabled)
            {
                //撤销
                //当前可以保存修改， 那么再点这个按钮就是撤销
                DocFormHelper.SetSaveStatus(SaveStatus.ReadOnly, this, this.toolSave, this.toolModify, this.toolSaveModify);

                //删除正在编辑记录
                EditingBll.Clear(this.Doc);

            }
            else
            {
                // 这时, 这个按钮是显示的文字是"修改", 
                //检查权限 不是自己的单据需要额外的权限
                if (this.Doc.PreparedBy != UserBll.CurrentUser.Name
                    && UserBll.CheckRight(this.DocBll.ModifyPermission) == false)
                {
                    MessageBox.Show(shop.Model.CN.Msg_NoRightToModifyOther, Properties.Resources.systemInformation, MessageBoxButtons.OK,
                        MessageBoxIcon.Warning);
                    this.sta_Err.SetMessage(shop.Model.CN.Msg_NoRightToModifyOther, true);
                }
                else
                {
                    //检查是否可以修改 
                    var status = this.DocBll.GetStatus(this.Doc);
                    if (status.EnableModify == false)
                    {
                        MessageBox.Show(status.Reason, Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.sta_Err.SetMessage(status.Reason, true);
                        return;
                    }

                    //添加正在编辑记录
                    if (EditingBll.TryAdd(this.Doc, UserBll.CurrentUser, out var editing) == false)
                    {
                        string err = string.Format(shop.Model.CN.Msg_DocIsEditingByOther, editing.UserName, editing.EditTime);
                        MessageBox.Show(err, Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.sta_Err.SetMessage(err, true);
                    }
                    else
                    {
                        //改变单据编辑状态
                        DocFormHelper.SetSaveStatus(SaveStatus.CanModify, this, this.toolSave, this.toolModify, this.toolSaveModify);
                        MessageTip.ShowOk(this, shop.Model.CN.Msg_docCanEdit);   // "可以编辑了!"
                    }

                }

            }
        }

        /// <summary> 保存修改 </summary>
        private void toolSaveModify_Click(object sender, EventArgs e)
        {
            //直接保存修改
            this.Save();
        }



        private void toolRefresh_Click(object sender, EventArgs e)
        {
            if (this.Doc != null)
            {
                this.Doc = this.DocBll.GetDoc(this.Doc.DocId);
            }
        }



        #region 打印

        /// <summary> 打印预览 </summary>
        private void toolPrintPreView_Click(object sender, EventArgs e)
        {
            if (this.Doc != null && this.Doc.DocId == 0)
            {
                MessageBox.Show(shop.Model.CN.Msg_SaveBeforePrint, Resources.systemInformation, MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                return;
            }

            this.PrintDoc(true);
        }

        /// <summary> 打印 </summary>
        private void toolPrint_Click(object sender, EventArgs e)
        {
            if (this.Doc != null && this.Doc.DocId == 0)
            {
                MessageBox.Show(shop.Model.CN.Msg_SaveBeforePrint, Resources.systemInformation, MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                return;
            }

            this.PrintDoc(false);
        }

        /// <summary> 打印 </summary>
        /// <param name="isPreview">是否预览</param>
        private void PrintDoc(bool isPreview)
        {
            //GtPrintEditor.GtPrintDocument printFile = GtPrintDocument.FromFile("合同结算模板");
            //if (printFile == null)
            //{
            //    MessageBox.Show(shop.Model.CN.Msg_CannotFindPrintTemplate, Resources.systemInformation, MessageBoxButtons.OK,
            //    MessageBoxIcon.Information);
            //    return;
            //}

            //// todo 参数按照模板进行调整 参数 
            //PrintParameter[] prs = new PrintParameter[]
            //{
            //    new PrintParameter("time"){ Value = DateTime.Now},
            //    new PrintParameter("打印次数"){ Value = this.Doc.PrintCount +1}, 
            //    new PrintParameter("doc"){ Value = this.Doc},
            //};

            //// todo 模板未实现这个代码 修改打印次数
            //// printFile.PrintSuccess += d =>  this.DocBll.AddPrintCount(this.Doc);      //PrintSuccess是打印成功事件

            //if (isPreview)
            //    printFile.PrintPreView(prs); //预览
            //else
            //    printFile.PrintChoosePrinter(prs);        //打印, 会提示先择打印机
        }

        #endregion


        /// <summary> 审核 </summary>
        private void toolCheck_Click(object sender, EventArgs e)
        {
            if (this.DocBll.CheckDocument(this.Doc, UserBll.CurrentUser, out var err) == true)
            {
                this.sta_Err.SetMessage();
                MessageTip.ShowOk(this, shop.Model.CN.Msg_ISchecked);    // "单据已审核！"
            }
            else
            {
                MessageBox.Show(err, Properties.Resources.systemInformation, MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                this.sta_Err.SetMessage(err, true);
            }
        }

        /// <summary> 反审核 </summary>
        private void toolUnCheck_Click(object sender, EventArgs e)
        {
            if (this.DocBll.UnCheckDocument(this.Doc, UserBll.CurrentUser, out var err) == true)
            {
                this.sta_Err.SetMessage();
                MessageTip.ShowOk(this, shop.Model.CN.Msg_DocIsUnCheck); // "单据已反审核！"
            }
            else
            {
                MessageBox.Show(err, Properties.Resources.systemInformation, MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                this.sta_Err.SetMessage(err, true);
            }
        }

        private void toolDelete_Click(object sender, EventArgs e)
        {
            this.Delete();
        }

        #endregion 上方菜单按钮

        #region 其他按钮



        private void btn_showQueryBox_Click(object sender, EventArgs e)
        {
            if (this.ParentForm is DocDockxx dd)
            {
                dd.toolQuery.PerformClick();  //点击查询按钮
            }
        }

        #endregion 其他按钮

        #region 实现合并工具栏的接口

        /// <summary> 实现合并工具栏的接口 </summary>
        public ToolStrip MergedToolStrip => this.toolStrip1;

        #endregion 实现合并工具栏的接口

        #region 窗体事件

        /// <summary> 窗体关闭事件 </summary>
        private void Form_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.grid.SaveWidthIni(this.GetType().Name);

            //如果当前正在编辑状态， 需要删除正在编辑记录
            if (this.toolSaveModify.Enabled)
                EditingBll.Clear(this.Doc);
        }

        private void Form_Load(object sender, EventArgs e)
        {
            this.grid.ReLoadWidthIni(this.GetType().Name);

        }


        #endregion 窗体事件



        private void grid_CellEndEdit(object sender, unvell.ReoGrid.CellEndEditEventArgs e)
        {
            try
            {
                if (e.Cell.Column == cl_LogiAccount.Index)
                {
                    GetLogi(e.Cell.Row, grid[e.Cell].IsNull(), false);
                }
                //else if (e.Cell.Column == cl_AddPrice.Index )
                //{

                //}
                //else if (e.Cell.Column == cl_MaxQty2.Index)
                //{


                //}
            }
            catch (Exception)
            {

                throw;
            }
        
        }

        private async void GetLogi(int rowIndex, string arg2, bool isKey)
        {
            if (string.IsNullOrEmpty(arg2) && !isKey) //内容空的, 直接退出
            {
                //将单据内容关联属性清空
                grid[cl_LogiAccount.Index, rowIndex] = "";

                return;
            }

            var bll = new LogiInfoBll();
            var col = new Dictionary<string, string>()
            {
                {nameof(LogiInfo.LogiAcct),"快递账户" },
                {nameof(LogiInfo.IsAgent),"是否代发" },
                {nameof(LogiInfo.logistics_name),"快递名称" },
                //{nameof(LogiInfo.logistics_name),"快递名称" },
            };

            var res = await new Selector<LogiInfo>()
                .UseSearchAsync(a => bll.Query(a.FirstOrDefault()))
                .UseColumns(col)
                .FindText(arg2)
                .GetValueAsync();

            if (res.IsOk)
            {
                grid[cl_LogiAccount.Index, rowIndex] = res.Data.LogiAcct;
            }
            else
            {
                grid[cl_LogiAccount.Index, rowIndex] = "";
            }
        }


        private bool CheckMethod(int row)
        {
            bool bl = true;
            var str = grid[cl_Method, row].IsNull();
            //switch (str)
            //{
            //    case "均摊":
            //        if (grid[cl_AddPrice,row].IsNull(0m)!=0 || grid[cl_AddPrice2, row].IsNull(0m) != 0)
            //        {
            //            MessageBox.Show("均摊方式下, 加价不能有数据!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //            bl = false;
            //        }
            //        break;
            //    case "按金额加价":
            //    case "按数量加价":
            //    case "按重量加价":
            //        if (grid[cl_AddPrice, row].IsNull(0m) == 0 || grid[cl_AddPrice2, row].IsNull(0m) == 0)
            //        {
            //            MessageBox.Show($"{str}方式下, 加价不能是0 !", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //            bl = false;
            //        }
            //        break;
            //}

            return bl;
        }


        private void grid_CellKeyUp(object sender, unvell.ReoGrid.Events.CellKeyDownEventArgs e)
        {
            if (e.Cell.Row<1)
            {
                return;
            }

            if (e.Cell.Column == cl_LogiAccount.Index)
            {
                GetLogi(e.Cell.Row, null, true);
            }
        }





        private void btn_FromExcel_Click(object sender, EventArgs e)
        {
            //var form = new OpenFileDialog()
            //{
            //    Filter = "Excel文件|*.xlsx;*.xls;*.xlsm",
            //    Title = "打开表格文件",
            //    CheckFileExists = true,
            //};
            //if (form.ShowDialog() == DialogResult.OK)
            //{
            //    var res = ExcelHelper.Import(form.FileName, null, 1, 2, false, false);
            //    if (res == null)
            //    return;

            //    //账户, 时间, 金额, 客户, 开票单位, 类别, 备注, 标记

            //    var jBll = new BLL.BasicInfo.JBankBll();
            //    var cBll = new BLL.BasicInfo.JCustomerBll();

            //    try
            //    {
            //        var list = res.AsEnumerable()
            //            .Select(a => new SalesAmount()
            //            {
            //                BankNumber = a.Field<string>(0),
            //                OccurDate = a.Field<string>(1)?.IsNullDate((DateTime?)null),
            //                Amount = a.Field<object>(2)?.IsNull(0m),
            //                Customer = a.Field<string>(3),
            //                Company = a.Field<string>(4),
            //                Flag = a.Field<string>(5),
            //                Remarks = a.Field<string>(6),
            //                IsTax = a.Field<string>(7),
            //            })
            //            .Where(a=> string.IsNullOrEmpty(a.Customer) == false || a.Amount != null || string.IsNullOrEmpty( a.Company ) == false || string.IsNullOrEmpty(a.BankNumber) == false)
            //            .ToList();

            //        foreach (var item in list)
            //        {
            //            var find = Doc.Items.FirstOrDefault(a => string.IsNullOrEmpty(a.BankAccount) == false && a.BankNumber == item.BankNumber);
            //            if (find == null)
            //            {
            //                var bank = jBll.GetByNum(item.BankNumber);
            //                item.BankAccount = bank == null ? "" : bank.Name;
            //                item.BankNumber = bank == null ? item.BankNumber : bank.ShortNumber;
            //                item.Cardholder = bank == null ? "" : bank.Contact;
            //            }
            //            else
            //            {
            //                item.BankAccount = find.BankAccount;
            //                item.BankNumber = find.BankNumber;
            //                item.Cardholder = find.Cardholder;
            //            }

            //            //
            //            find = Doc.Items.FirstOrDefault(a => string.IsNullOrEmpty(a.CustomerId) == false && a.Customer== item.Customer);
            //            if (find == null)
            //            {
            //                var cus = cBll.GetByName(item.Customer);
            //                if (cus != null)
            //                {
            //                    item.Customer = cus.Name;
            //                    item.CustomerId = cus.Code;
            //                }
            //                else
            //                {
            //                    item.Customer = "";
            //                    item.CustomerId = "";
            //                }
            //            }
            //            else
            //            {
            //                item.CustomerId = find.CustomerId;
            //            }
            //        }

            //        this.Doc.Items.AddRange(list);

            //        this.grid.ResetBindings(false);

            //        // todo 
            //        grid[cl_BankAccount, 0] = Doc.Items[0].BankAccount;
            //        grid[cl_BankNumber, 0] = Doc.Items[0].BankNumber;
            //        grid[cl_Customer, 0] = Doc.Items[0].Customer;
            //        grid[cl_CustomerId, 0] = Doc.Items[0].CustomerId;
            //        grid[cl_Cardholder, 0] = Doc.Items[0].Cardholder;
            //        grid[cl_Amount, 0] = Doc.Items[0].Amount;
            //        grid[cl_OccurDate, 0] = Doc.Items[0].OccurDate;
            //        grid[cl_IsTax, 0] = Doc.Items[0].IsTax;
            //        grid[cl_Company, 0] = Doc.Items[0].Company;

            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show("导入数据出现错误:" + ex.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    }
            //}
        }
    }






}


 
